package com.itheima.core;

import com.itheima.core.domain.Configuration;
import com.itheima.core.domain.Mapper;
import com.itheima.core.inter.SqlSession;
import com.itheima.core.utils.Executor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.Map;

/**
 * @author slstart
 * @create 2021-05-04 14:03
 */
public class DefaultSqlSession implements SqlSession {
    private Configuration cfg;

    public DefaultSqlSession(Configuration cfg) {
        this.cfg = cfg;
    }

    public  List selectList(String namespaceId) throws Exception {
        //获取所有SQL和返回值
        Map<String, Mapper> mappers = cfg.getMappers();
        //根据名称空间和id,获取要执行的SQL语句
        Mapper mapper = mappers.get(namespaceId);
        //获取要执行的SQL语句和返回值
        String sql = mapper.getSql();
        String resultType = mapper.getResultType();

        List list = new Executor(cfg).executeQuery(sql, resultType);
        return list;
    }

    public <E> E getMapper(Class<E> clazz) {
//        String name = clazz.getName();
        E e = (E) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{clazz}, new InvocationHandler() {

            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Class<?> clazz = method.getDeclaringClass();
                String name = clazz.getName();
                String methodName = method.getName();
                String namespaceId = name + "."+methodName;
                Mapper mapper = cfg.getMappers().get(namespaceId);
                String sql = mapper.getSql();
                String resultType = mapper.getResultType();
                List list = null;
                if(sql.trim().startsWith("select")){
                     list = new Executor(cfg).executeQuery(sql, resultType);
                }
                return list;
            }
        });
        return e;
    }


}
